package com.mls.fivedistrict.controller.backend;

import com.mls.fivedistrict.common.PageFilter;
import com.mls.fivedistrict.common.ServiceResponse;
import com.mls.fivedistrict.controller.BaseController;
import com.mls.fivedistrict.pojo.OrePool;
import com.mls.fivedistrict.pojo.ProductPlan;
import com.mls.fivedistrict.server.OrePoolService;
import com.mls.fivedistrict.server.ProductPlanService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * Created by chenxiuxiang on 2018/4/1.
 */
@RestController
@RequestMapping("/api/manager")
public class ProductPlanController extends BaseController {
    @Resource(name = "productPlanService")
    ProductPlanService productPlanService;
    @Resource(name = "orePoolService")
    OrePoolService orePoolService;

    @GetMapping("/v1/productPlans")
    public ServiceResponse getProductList(HttpServletRequest httpServletRequest) {
        PageFilter pageFilter = getPageFilter();
        return productPlanService.getProductPlan(pageFilter);
    }

    @PutMapping("/v1/productPlan/{productPlanId}")
    public ServiceResponse AddTotalProduct(@PathVariable("productPlanId") Long productPlanId, @RequestBody ProductPlan productPlan) {
        productPlan.setId(productPlanId);
        ProductPlan srcProductPlan = productPlanService.getProductPlanById(productPlanId);
        if (productPlan.getTotal() != null) {
            OrePool orePool = productPlanService.getPoolByProductId(productPlanId);
            BigDecimal total = orePoolService.getAllPlanTotalByOrePoolId(orePool.getId());
            total = total.subtract(srcProductPlan.getTotal());
            total = total.add(productPlan.getTotal());
            if (total.compareTo(orePool.getTotal()) <= 0) {
                productPlan.setResidue(productPlan.getTotal());
                return productPlanService.editProductPlan(productPlan);
            }
        } else if (productPlan.getFrequency() != null) {
            return productPlanService.editProductPlan(productPlan);
        }
        return ServiceResponse.createErrorResponse();
    }
}
